package com.zidian.study.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.zidian.study.activity.InteractionAskDetailActivity;
import com.zidian.study.adapter.CourseClassAdapter;
import com.zidian.study.bean.StudentClassBean;
import com.zidian.study.globa.BaseFragment;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/23 0023.
 * 蹭课
 */
public class CourseClassFragment extends BaseFragment {


    public SwipeRefreshLayout mSwipeRefreshWidget;
    private RecyclerView mRecyclerView;


    private boolean isLoading;
    private boolean isRefreshing = false;
    private List<StudentClassBean.DataBean> data = new ArrayList<>();
    private CourseClassAdapter adapter;
    private Handler handler = new Handler();
    private int page = 1;


    /**
     * 实现父类的方法，传入布局
     *
     * @return 布局id
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_course_add;
    }


    /**
     * 实例化fragment
     *
     * @return
     */
    public static CourseClassFragment newInstance() {
        return new CourseClassFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        adapter = new CourseClassAdapter(getActivity(), data);
        mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.list);

        initView();
        initData();


    }

    /**
     * 重载方法初始化View的显示
     * 分离view的初始化模块，方便维护
     */
    public void initView() {


        mSwipeRefreshWidget.setColorSchemeResources(R.color.green);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                isRefreshing = true;
                mSwipeRefreshWidget.setRefreshing(true);
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        page = 1;
                        isRefreshing = true;
                        getData();
                    }
                }, 2000);
            }
        });
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page++;
                                getData();
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new CourseClassAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
                startActivity(InteractionAskDetailActivity.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        adapter.setOnButtonClickListener(new CourseClassAdapter.OnButtonClickListener() {
            @Override
            public void onAddClick(String courseId, String teacherName, int position) {
                addCourse(courseId, teacherName, position);
            }

            @Override
            public void onDeleteClick(String courseId, String teacherName, int position) {
                deleteCourse(courseId, position);
            }

        });

    }

    /**
     * 初始化数据
     */
    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }, 1500);

    }

    /**
     * 获取测试数据
     */
    private void getData() {
        String loginUrl = Constant.URL_GOAL + "rubLesson/selectType";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", page + "");
        map.put("pageSize", "10");
        map.put("token", GetUserInfo.getToken(mActivity));
        map.put("studentId", GetUserInfo.getStudentId(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(mActivity.getApplication(), "获取课程信息失败！");
                        return;
                    }

                } catch (JSONException e) {

                }

                Log.e("T", response);

                Gson gson = new Gson();
                StudentClassBean model = gson.fromJson(response, StudentClassBean.class);
                if (model.isSuccess()) {
                    if (model.getData().size() < 10) {
                        isLoading = true;
                        adapter.setHasMore(false);
                    } else {
                        isLoading = false;
                        adapter.setHasMore(true);
                    }
                    data.addAll(model.getData());
                    adapter.notifyDataSetChanged();
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });


    }

    private void addCourse(String courseId, String teacherName, final int position) {

        String loginUrl = Constant.URL_GOAL + "rubLesson/addType";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherName", teacherName);
        map.put("token", GetUserInfo.getToken(mActivity));
        map.put("studentId", GetUserInfo.getStudentId(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(mRecyclerView, "添加蹭课失败！", Snackbar.LENGTH_SHORT).show();
                        return;
                    } else {
                        data.get(position).setTypeNum(Integer.parseInt(data.get(position).getTypeNum()) + 1 + "");
                        data.get(position).setCourseType(1);
                        Snackbar.make(mRecyclerView, "添加蹭课成功！", Snackbar.LENGTH_SHORT).show();
                        adapter.notifyDataSetChanged();
                    }

                } catch (JSONException e) {

                }

                Log.e("T", response);

            }
        });


    }

    private void deleteCourse(String courseId, final int position) {

        String loginUrl = Constant.URL_GOAL + "rubLesson/deleteType";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("token", GetUserInfo.getToken(mActivity));
        map.put("studentId", GetUserInfo.getStudentId(mActivity));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(mRecyclerView, "取消蹭课失败！", Snackbar.LENGTH_SHORT).show();
                        return;
                    } else {
                        data.get(position).setTypeNum(Integer.parseInt(data.get(position).getTypeNum()) - 1 + "");
                        data.get(position).setCourseType(0);
                        Snackbar.make(mRecyclerView, "取消蹭课成功！", Snackbar.LENGTH_SHORT).show();
                        adapter.notifyDataSetChanged();
                    }

                } catch (JSONException e) {

                }

                Log.e("T", response);

            }
        });

    }


}


